#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define KEY 6
char *keyword[KEY] = {"for", "if", "then", "else", "while", "do"};
char id[1024];
int num;
int token;

void lexical(FILE *fp) {
    char x = getc(fp);
	num = 0;
	strcpy(id, "\0");
	while(x==' '||x=='\t'||x=='\n')
		x=getc(fp);
	if(x>='0'&&x<='9')
	{
		int i=0;
		for(;x>='0'&&x<='9';x=getc(fp))
			id[i++]=x;
		id[i]='\0';
		num=atoi(id);
		token=11;
		ungetc(x, fp);
	}
	else if((x>='a'&&x<='z')||(x>='A'&&x<='Z'))
	{
		int i=0;
		for(;(x>='a'&&x<='z')||(x>='A'&&x<='Z')||(x>='0'&&x<='9');x=getc(fp))
			id[i++]=x;
		id[i]='\0';
		token=10;
		int j=0;
		for(j=0;j<6;j++)
		{
			if(strcmp(keyword[j],id)==0)
			{
				token=j+1;
				break;
			}
		}
		ungetc(x, fp);
	}
	else
	{
		int i=0;
		switch(x)
		{
		case '+':token=13;id[i++]='+';break;
		case '-':token=14;id[i++]='-';break;
		case '*':token=15;id[i++]='*';break;
		case '/':token=16;id[i++]='/';break;
		case ':':token=17;id[i++]=':';
				x=getc(fp);
				if(x=='=')
				{
					token=18;
					id[i++]='=';
				}
				else
					ungetc(x, fp);
				break;
		case '<':token=20;id[i++]='<';
				x=getc(fp);
				if(x=='>')
				{
					token=21;
					id[i++]='>';
				}
				else if(x=='=')
				{
					token=22;
					id[i++]='=';
				}
				else
					ungetc(x, fp);
				break;
		case '>':token=23;id[i++]='>';
				x=getc(fp);
				if(x=='=')
				{
					token=24;
					id[i++]='=';
				}
				else
					ungetc(x, fp);
				break;
		case '=':token=25;id[i++]='=';break;
		case ';':token=26;id[i++]=';';break;
		case '(':token=27;id[i++]='(';break;
		case ')':token=28;id[i++]=')';break;
		case '#':token=0;id[i++]='#';break;
		default:break;
		}
		id[i]='\0';
	}

	//process x
	//process each regex here
	//store the result in global variables id, num, or token
	//in case of backtrack, use
	//ungetc(x, fp);
	
}

int main(int argc, const char *argv[])
{
	if(argc < 2) {
		printf("insufficient args\n");
		return 1;
	}
	FILE *fp = fopen(argv[1], "r");
	do {
		lexical(fp);
		switch(token) {
			case 10: printf("(id, %s)\n", id); break;
			case 11: printf("(num, %d)\n", num); break;
			case -1: printf("error!\n"); break;
			default: printf("(%d, %s)\n", token, id); 		
		}
	} while(token != 0);
	

	fclose(fp);
	return 0;
}
